import { Breadcrumb, Button, Table, Space, Modal, message, TableProps, Row, Col, Popover } from 'antd';
import { DownOutlined } from '@ant-design/icons';
import React, { FC } from 'react';
import {
  FormPanel,
  ExtendReader,
  type FormPanelObject,
  InputType,
  FormPanelBtnAlign,
  FormPanelBtnDisplay,
  Utils,
  StandUploadExcel,
  RuleType,
} from 'lfun-bg-comp';
import { useNavigate } from 'react-router-dom';
import dayjs from 'dayjs';
import _ from 'lodash';
import { PageContainer } from '@/component/page-container';
import { GENDER, YES_NO } from '@/constant/basicOptions';
import { EDUCATIONAL_BACKGROUND, HIGHEST_EDUCATION, HUMANNESS, STAFFING_ARRANGEMENT } from '@/constant/teachOptions';
import { ID_TYPE, POLITICAL_STATUS } from '@/constant/studentOptions';
import { PAGINATIONCONFIG } from '@/constant/page';
import { NewTeachersSrv, TeachersSrv } from '@/service/teacher';
import utils, { getPathRoot, get_stoge_pz, set_stoge_pz } from '@/utils';
import { searchSchoolOptions } from '@/service/options';
import { APPROVAL_STATUS, IMPORT_EXCEL_TEMPLATE } from '@/constant';
import PermissionButton, { isPermission, isPermissionOperate, isPermissions } from '@/component/permission-button';
import styles from './index.less';

const Groups: FC = () => {
  const [loading, setLoading] = React.useState(false);
  const [data, setData] = React.useState([
    {
      teacher_name: '暂无数据',
      teacher_id: 1,
      teacher_base_id: '',
      teacher_date_of_birth: '',
      teacher_id_number: '',
    },
  ]);
  const [total, setTotal] = React.useState(0);
  const [pageSize, setPageSize] = React.useState(get_stoge_pz());
  const [pageIndex, setPageIndex] = React.useState(1);
  const [form, setForm] = React.useState(null);
  const [showNewModel, setShowNewModel] = React.useState(false);
  const [expand, setExpand] = React.useState(false);
  const navigate = useNavigate();
  const isSchool = Utils.getProps('isSchool');

  const handleView = record => {
    navigate(`${getPathRoot()}/onboarding/details/${record.teacher_id}`, { state: { ...record } });
  };
  const handleEdit = record => {
    navigate(`${getPathRoot()}/onboarding/edit/${record.teacher_id}`, { state: { ...record } });
  };
  const handleDelete = async record => {
    // content 按最字段内容为准，格式是否删除${证件类型}:${证件号码},姓名${姓名}的教师信息?
    await Modal.confirm({
      title: '删除',
      content: `是否删除身份证${record.teacher_id_number},姓名:${record.teacher_name}的教师信息?`,
      onOk: async () => {
        console.log('OK');
        if (!record.teacher_id) {
          return;
        }
        await NewTeachersSrv.delete(record.teacher_id);
        fetchData({ ...form?.getFieldsValue(), page: pageIndex, per_page: pageSize });
      },
    });
  };
  const handleReset = record => {
    navigate(`${getPathRoot()}/onboarding/restdetails/${record.teacher_id}`, { state: { ...record } });
  };

  const pageChange = (page, per_page) => {
    set_stoge_pz(per_page);
    fetchData({ ...form?.getFieldsValue(), page, per_page });
  };

  const columns: TableProps['columns'] = [
    {
      title: '教职工编码',
      dataIndex: 'teacher_code',
      key: 'teacher_code',
    },
    {
      title: '姓名',
      dataIndex: 'teacher_name',
      key: 'teacher_name',
    },
    {
      title: '性别',
      dataIndex: 'teacher_gender',
      key: 'teacher_gender',
    },
    {
      title: '教职工号',
      dataIndex: 'teacher_id',
      key: 'teacher_id',
    },
    {
      title: '手机号',
      dataIndex: 'teacher_mobile',
      key: 'teacher_mobile',
    },
    {
      title: '身份证号',
      dataIndex: 'teacher_id_number',
      key: 'teacher_id_number',
    },
    {
      title: '任职单位',
      dataIndex: 'school_name',
      key: 'school_name',
    },
    // {
    //   title: '办别',
    //   dataIndex: 'school_name',
    //   key: 'school_name',
    // },
    {
      title: '行政归属地',
      dataIndex: 'school_name',
      key: 'school_name',
    },
    {
      title: '用人性质',
      dataIndex: 'employment_form',
      key: 'employment_form',
      render: (text: any) => {
        return _.find(STAFFING_ARRANGEMENT, { value: String(text) })?.label;
      },
    },
    {
      title: '操作',
      key: 'actions',
      align: 'center',
      width: 280,
      fixed: 'right',
      render: (text, record) => {
        return (
          <>
            <Button type="link" onClick={() => handleEdit(record)}>
              编辑
            </Button>
            <Button type="link" onClick={() => handleView(record)}>
              查看
            </Button>
            <Button type="link" onClick={() => handleDelete(record)}>
              删除
            </Button>
          </>
        );
      },
    },
    // {
    //   title: '工作单位',
    //   dataIndex: 'school_name',
    //   key: 'school_name',
    // },
    // {
    //   title: '最高学历',
    //   dataIndex: 'highest_education',
    //   key: 'highest_education',
    //   render: (text: any) => {
    //     text = _.isArray(text) ? text : text.split(',');
    //     const arr: any[] = text.map(v => utils.findLabelDeep(HIGHEST_EDUCATION, String(v)));
    //     return arr.join('-');
    //   },
    // },
    // {
    //   title: '政治面貌',
    //   dataIndex: 'political_status',
    //   key: 'political_status',
    //   render: (text: any) => {
    //     return _.find(POLITICAL_STATUS, { value: String(text) })?.label;
    //   },
    // },
    // {
    //   title: '是否在编',
    //   dataIndex: 'in_post',
    //   key: 'in_post',
    //   render: (text: any) => {
    //     return _.find(YES_NO, { value: text })?.label;
    //   },
    // },
    // {
    //   title: '用工性质',
    //   dataIndex: 'employment_form',
    //   key: 'employment_form',
    //   render: (text: any) => {
    //     return _.find(STAFFING_ARRANGEMENT, { value: String(text) })?.label;
    //   },
    // },
    // {
    //   title: '入职时间',
    //   dataIndex: 'enter_school_time',
    //   key: 'enter_school_time',
    // },
    // {
    //   title: '审批状态',
    //   dataIndex: 'approval_status',
    //   key: 'approval_status',
    //   render: (text: any) => {
    //     return _.find(APPROVAL_STATUS, { value: text })?.label;
    //   },
    // },
    // {
    //   title: '操作',
    //   key: 'actions',
    //   align: 'center',
    //   //width: 280,
    //   fixed: 'right',
    //   hidden: !isPermissionOperate(),
    //   render: (text, record) => (
    //     <Space size="small">
    //       <PermissionButton permission="view">
    //         <Button type="link" onClick={() => handleView(record)}>
    //           查看
    //         </Button>
    //       </PermissionButton>
    //       {isSchool && record.teacher_sub_status === 'unsubmitted' && (
    //         <PermissionButton permission="edit">
    //           <Button type="link" onClick={() => handleEdit(record)}>
    //             编辑
    //           </Button>
    //         </PermissionButton>
    //       )}
    //       {isSchool && record.teacher_sub_status === 'unsubmitted' && (
    //         <PermissionButton permission="delete">
    //           <Button type="link" onClick={() => handleDelete(record)}>
    //             删除
    //           </Button>
    //         </PermissionButton>
    //       )}
    //       {isSchool && record.approval_status === 'progressing' && (
    //         <PermissionButton permission="revoke">
    //           <Button type="link" onClick={() => handleReset(record)}>
    //             撤回
    //           </Button>
    //         </PermissionButton>
    //       )}
    //       {isSchool && record.teacher_sub_status === 'unsubmitted' && record.approval_status === 'rejected' && (
    //         <PermissionButton permission="edit">
    //           <Button type="link" onClick={() => handleEdit(record)}>
    //             再次提交
    //           </Button>
    //         </PermissionButton>
    //       )}
    //     </Space>
    //   ),
    // },
  ];
  const list = [
    {
      title: '',
      labelCol: { span: 7 },
      wrapperCol: { span: 17 },
      span: 24,
      inputs: [
        {
          label: '姓名',
          name: 'teacher_name',
          key: 'teacher_name',
          required: true,
          textRange: [0, 20],
        },
        {
          label: '手机号',
          name: 'mobile',
          key: 'mobile',
          required: true,
          ruleType: RuleType.cnPhone,
        },
        {
          label: '身份证件类型',
          name: 'teacher_id_type',
          key: 'teacher_id_type',
          required: true,
          inputType: InputType.select,
          relationFields: ['teacher_id_number'],
          renderOption: ID_TYPE,
        },
        {
          label: '身份证件号码',
          name: 'teacher_id_number',
          key: 'teacher_id_number',
          relationFields: ['teacher_date_of_birth', 'teacher_gender'],
          textRange: [0, 30],
          required: true,
          ruleType: (formObjectPanel: FormPanelObject) => {
            const id_type = formObjectPanel.getFieldValue('teacher_id_type');
            if (id_type === 'resident_id_card') {
              return 'cnPeopleNo';
            }
            return '';
          },
          renderValidate: (formObjectPanel: FormPanelObject) => {
            const id_type = formObjectPanel.getFieldValue('teacher_id_type');
            if (id_type === 'resident_id_card') {
              return ExtendReader.validateCnPeopleNo(
                formObjectPanel.getFieldValue('teacher_id_number'),
                formObjectPanel.getFieldValue('teacher_date_of_birth'),
                formObjectPanel.getFieldValue('teacher_gender')
              );
            }
            return '';
          },
        },
        {
          label: '出生年月',
          name: 'teacher_date_of_birth',
          key: 'teacher_date_of_birth',
          relationFields: ['teacher_id_number'],
          inputType: InputType.date,
          required: true,
          render: (formObjectPanel: FormPanelObject) => {
            const id_type = formObjectPanel.getFieldValue('teacher_id_type');
            if (id_type !== 'resident_id_card') {
              return formObjectPanel.getFieldValue('teacher_date_of_birth');
            }
            return ExtendReader.renderBirthday('teacher_id_number', 'teacher_date_of_birth', formObjectPanel);
          },
        },
        {
          label: '性别',
          name: 'teacher_gender',
          key: 'teacher_gender',
          relationFields: ['teacher_id_number'],
          required: true,
          inputType: InputType.select,
          renderOption: GENDER,
          render: (formObjectPanel: FormPanelObject) => {
            const id_type = formObjectPanel.getFieldValue('teacher_id_type');
            if (id_type !== 'resident_id_card') {
              return formObjectPanel.getFieldValue('teacher_gender');
            }
            return ExtendReader.renderGender('teacher_id_number', 'teacher_gender', formObjectPanel);
          },
        },
        // {
        //   label: '任职单位',
        //   name: 'teacher_employer',
        //   key: 'teacher_employer',
        //   required: true,
        //   inputType: InputType.search,
        //   renderOption: searchSchoolOptions,
        //   formatSubmitValue: val => {
        //     if (typeof val === 'object') {
        //       return val.value;
        //     }
        //     return val;
        //   },
        // },
      ],
    },
  ];

  const searchList = [
    {
      title: '',
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
      inputs: [
        {
          label: '教职工编码',
          name: 'teacher_code',
          key: 'teacher_code',
          textRange: [0, 20],
        },
        {
          label: '姓名',
          name: 'teacher_name',
          key: 'teacher_name',
          textRange: [0, 20],
        },
        {
          label: '性别',
          name: 'teacher_gender',
          key: 'teacher_gender',
          inputType: InputType.select,
          renderOption: GENDER,
        },
        {
          label: '国籍/地区',
          name: 'teacher_nationality',
          key: 'teacher_nationality',
          inputType: InputType.select,
          renderOption: GENDER,
        },
        {
          label: '手机号',
          name: 'teacher_mobile',
          key: 'teacher_mobile',
          textRange: [0, 20],
        },
        {
          label: '身份证类型',
          name: 'teacher_id_type',
          key: 'teacher_id_type',
          inputType: InputType.select,
          renderOption: GENDER,
        },
        {
          label: '身份证号',
          name: 'teacher_id_number',
          key: 'teacher_id_number',
          textRange: [0, 18],
        },
        {
          label: '政治面貌',
          name: 'political_status',
          key: 'political_status',
          inputType: InputType.select,
          renderOption: POLITICAL_STATUS,
        },
        {
          label: '最高学历',
          name: 'highest_education',
          key: 'highest_education',
          inputType: InputType.cascader,
          renderOption: EDUCATIONAL_BACKGROUND,
        },
        {
          label: '出生日期',
          name: 'teacher_date_of_birth',
          key: 'teacher_date_of_birth',
          inputType: InputType.date,
        },
        {
          label: '教职工来源',
          name: 'teacher_source',
          key: 'teacher_source',
          inputType: InputType.select,
          renderOption: GENDER,
        },
        {
          label: '是否在编',
          name: 'teacher_onboarding',
          key: 'teacher_onboarding',
          inputType: InputType.select,
          renderOption: GENDER,
        },
        {
          label: '用人形式',
          name: 'teacher_employment_form',
          key: 'teacher_employment_form',
          inputType: InputType.select,
          renderOption: GENDER,
        },
        {
          label: '教师资格证',
          name: 'teacher_qualification_certificate',
          key: 'teacher_qualification_certificate',
          inputType: InputType.select,
          renderOption: GENDER,
        },
        {
          label: '是否县级及以上骨干教师',
          name: 'teacher_qualification_certificate',
          key: 'teacher_qualification_certificate',
          inputType: InputType.select,
          renderOption: GENDER,
        },
        {
          label: '教职工类别',
          name: 'teacher_category',
          key: 'teacher_category',
          inputType: InputType.select,
          renderOption: GENDER,
        },
        {
          label: '现任岗位类型',
          name: 'teacher_category',
          key: 'teacher_category',
          inputType: InputType.select,
          renderOption: GENDER,
        },
        {
          label: '现任岗位等级',
          name: 'teacher_category',
          key: 'teacher_category',
          inputType: InputType.select,
          renderOption: GENDER,
        },
        {
          label: '现任专业技术职务',
          name: 'teacher_category',
          key: 'teacher_category',
          inputType: InputType.select,
          renderOption: GENDER,
        },
        {
          label: '参加工作年月',
          name: 'teacher_date_of_employment',
          key: 'teacher_date_of_employment',
          inputType: InputType.date,
        },
        {
          label: '进校年月',
          name: 'enter_school_time',
          key: 'enter_school_time',
          inputType: InputType.dateRange,
          formatSubmitValue: (value, formPanelObject: FormPanelObject) => {
            ExtendReader.formatSubmitValueByDateRange(value, formPanelObject, 'enter_school_time');
            return null;
          },
        },

        // {
        //   label: '任职单位',
        //   name: 'teacher_employer',
        //   key: 'teacher_employer',
        //   inputType: InputType.search,
        //   renderOption: searchSchoolOptions,
        //   formatSubmitValue: val => {
        //     if (typeof val === 'object') {
        //       return val.value;
        //     }
        //     return val;
        //   },
        // },

        // {
        //   label: '是否在职',
        //   name: 'in_post',
        //   key: 'in_post',
        //   inputType: InputType.select,
        //   renderOption: YES_NO,
        // },
        // {
        //   label: '用人性质',
        //   name: 'employment_form',
        //   key: 'employment_form',
        //   inputType: InputType.select,
        //   renderOption: HUMANNESS,
        // },

        // {
        //   label: '审批状态',
        //   name: 'teacher_approval_status',
        //   key: 'teacher_approval_status',
        //   inputType: InputType.select,
        //   renderOption: APPROVAL_STATUS,
        // },
      ],
    },
  ];

  const searchTemplate = () => {
    const inputs = _.cloneDeep(searchList);
    inputs[0].inputs = expand ? inputs[0].inputs : inputs[0].inputs.slice(0, 9);
    return inputs;
  };

  React.useEffect(() => {
    fetchData({ page: pageIndex, per_page: pageSize });
  }, []);

  /** 获取数据 */
  const fetchData = async params => {
    console.log('🚀 ~ fetchData ~ params:', params);
    // 参数处理
    // 判断 highest_education 是不是数组，并且为真
    if (params.highest_education && Array.isArray(params.highest_education) && params.highest_education.length) {
      params.highest_education = params.highest_education.join(',');
    }
    if (params?.enter_school_time) {
      params.enter_school_time = dayjs(params.enter_school_time).format('YYYY-MM-DD');
    }

    setLoading(true);
    try {
      const { success, data } = await NewTeachersSrv.list(params);
      console.log('🚀 ~ fetchData ~ data:', data);
      if (success) {
        data.items.length ? setData(data.items) : setData([]);
        setTotal(data.total);
        setPageSize(params.per_page);
        setPageIndex(params.page);
      }
    } catch (error) {
      console.error('Error fetching data:', error);
    } finally {
      setLoading(false);
    }
  };
  /** 添加 */
  const handleAdd = async (formPanelObject: FormPanelObject) => {
    const params = formPanelObject.getFieldsValue();
    console.log('🚀 ~ handleAdd ~ params:', params);
    params.teacher_date_of_birth = dayjs(params.teacher_date_of_birth).format('YYYY-MM-DD');
    const res = await NewTeachersSrv.add(params);
    console.log('🚀 ~ handleAdd ~ res:', res);
    if (res.success) {
      message.success('添加成功');
      // const { data, success } = await NewTeachersSrv.infoAddSave({
      //   teacher_id: res.data.teacher_id,
      //   teacher_base_id: -1,
      // });
      // if (success) {
      formPanelObject.resetFields();
      navigate(`${getPathRoot()}/onboarding/edit/${res.data.teacher_id}`, {
        state: { ...res.data, teacher_base_id: res.teacher_base_id },
      });
      // } else {
      //   message.error('添加失败请稍后');
      // }
    } else {
      formPanelObject.reVaildation(res);
    }
  };

  const buildBtns = () => {
    return [
      <PermissionButton permission="export">
        <Button type="primary">导出</Button>
      </PermissionButton>,
      // <StandUploadExcel
      //   uploadSrv="/school/v1/storage/school-upload-uri"
      //   templateUrl={IMPORT_EXCEL_TEMPLATE.new_teachers}
      //   templateName="资源导入模版.xlsx"
      //   showExcelSrv="/school/v1/storage/file-data-preview"
      //   scene="new_teachers"
      //   onImport={async (data, file_name, bucket_name) => {
      //     const res = await NewTeachersSrv.importNewTeacher({
      //       file_name,
      //       bucket_name,
      //       scene: 'new_teachers',
      //     });
      //     if (res.success) {
      //       message.success('导入成功');
      //       fetchData({ ...{}, page: 1, per_page: pageSize });
      //     } else {
      //       message.error(res.message || res.details);
      //     }
      //   }}
      // >
      //   导入
      // </StandUploadExcel>,
    ];
  };

  const buttonsForm = () => {
    return [
      <a
        style={{ fontSize: 12 }}
        onClick={() => {
          setExpand(!expand);
        }}
      >
        <DownOutlined rotate={expand ? 180 : 0} /> {expand ? '收起' : '展开'}
      </a>,
    ];
  };
  const buttonsModel = () => {
    return [<Button type="primary">提交并继续补充信息</Button>];
  };

  return (
    <PageContainer header={<Breadcrumb items={[{ title: '新教职工管理' }]} />}>
      <FormPanel
        btnsAlign={FormPanelBtnAlign.right}
        restBtnText="重置"
        buttons={isSchool ? [...buildBtns(), ...buttonsForm()] : buttonsForm()}
        submitBtnText="查询"
        onFinish={(form: FormPanelObject) => {
          const params = form.getFieldsValue();
          fetchData({ ...params, page: 1, per_page: pageSize });
          setForm(form);
          return false;
        }}
        onReset={(form: FormPanelObject) => {
          fetchData({ page: 1, per_page: pageSize });
          form.resetFields();
        }}
        template={searchTemplate()}
      />
      <Row className={styles.extend_btns}>
        <Col span={12}>
          <Space align="center">
            <Button type="primary" onClick={() => setShowNewModel(true)}>
              新教职工登记
            </Button>
            <PermissionButton permission="entry">
              <Button type="primary" onClick={() => setShowNewModel(true)}>
                新教职工登记
              </Button>
            </PermissionButton>
            {isSchool && (
              <>
                <Popover
                  placement="bottom"
                  content={
                    <Row className={styles.tips_select}>
                      <Col span={24}>
                        {isPermission({ permission: 'importBaseInfo' }) && (
                          <StandUploadExcel
                            uploadSrv="/school/v1/storage/school-upload-uri"
                            templateUrl={IMPORT_EXCEL_TEMPLATE.teachers_basic}
                            templateName="资源导入模版.xlsx"
                            showExcelSrv="/school/v1/storage/file-data-preview"
                            scene="teachers_basic"
                            onImport={async (data, file_name, bucket_name) => {
                              const res = await TeachersSrv.importTeacherBasic({
                                file_name,
                                bucket_name,
                                scene: 'teachers_basic',
                              });
                              if (res.success) {
                                message.success('导入成功');
                                fetchData({ ...{}, page: 1, per_page: pageSize });
                                return true;
                              } else {
                                message.error(res.message || res.details);
                                return false;
                              }
                            }}
                          >
                            基础信息
                          </StandUploadExcel>
                        )}
                      </Col>
                      <Col span={24}>
                        {isPermission({ permission: 'importQuick' }) && (
                          <StandUploadExcel
                            uploadSrv="/school/v1/storage/school-upload-uri"
                            templateUrl={IMPORT_EXCEL_TEMPLATE.teachers_shortcut}
                            templateName="资源导入模版.xlsx"
                            showExcelSrv="/school/v1/storage/file-data-preview"
                            scene="teachers_shortcut"
                            onImport={async (data, file_name, bucket_name) => {
                              const res = await TeachersSrv.importTeacherShortcut({
                                file_name,
                                bucket_name,
                                scene: 'teachers_shortcut',
                              });
                              if (res.success) {
                                message.success('导入成功');
                                fetchData({ ...{}, page: 1, per_page: pageSize });
                                return true;
                              } else {
                                message.error(res.message || res.details);
                                return false;
                              }
                            }}
                          >
                            快捷导入
                          </StandUploadExcel>
                        )}
                      </Col>
                      {/* <Col span={24}>
                        {isPermission({ permission: 'importExtend' }) && (
                          <StandUploadExcel
                            uploadSrv="/school/v1/storage/school-upload-uri"
                            templateUrl={IMPORT_EXCEL_TEMPLATE.teachers_extend}
                            templateName="资源导入模版.xlsx"
                            showExcelSrv="/school/v1/storage/file-data-preview"
                            scene="teachers_extend"
                            onImport={async (data, file_name, bucket_name) => {
                              const res = await TeachersSrv.importTeacherExtend({
                                file_name,
                                bucket_name,
                                scene: 'teachers_extend',
                              });
                              if (res.success) {
                                message.success('导入成功');
                                fetchData({ ...{}, page: 1, per_page: pageSize });
                              } else {
                                message.error(res.message || res.details);
                              }
                            }}
                          >
                            扩展信息
                          </StandUploadExcel>
                        )}
                      </Col> */}
                    </Row>
                  }
                >
                  {isPermissions({ permission: ['importQuick', 'importBaseInfo'] }) && (
                    <Button type="primary">批量导入</Button>
                  )}
                </Popover>
              </>
            )}
          </Space>
        </Col>
      </Row>
      <Table
        dataSource={data}
        columns={columns}
        loading={loading}
        scroll={{ x: 'max-content' }}
        pagination={{ ...PAGINATIONCONFIG, total, pageSize, current: pageIndex, onChange: pageChange }}
      />
      <Modal title="新增教职工" footer={[]} open={showNewModel} onCancel={() => setShowNewModel(false)}>
        <FormPanel
          btnsAlign={FormPanelBtnAlign.center}
          buttonsDisplay={FormPanelBtnDisplay.block}
          restBtnText="返回"
          submitBtnText="确定"
          onReset={() => setShowNewModel(false)}
          template={list}
          buttons={buttonsModel()}
          onFinish={(formPanelObject: FormPanelObject) => {
            handleAdd(formPanelObject);
            return false;
          }}
        />
      </Modal>
    </PageContainer>
  );
};

export default Groups;
